﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Exporter.Models;
using ERPStore.Web.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Repositories
{
	public class SqlExporterRepository : CloudSoft.Repositories.SqlRepository<ExporterDbContext>
	{
		public IEnumerable<Models.BanishedProduct> GetBanishedProductListBySourceId(string sourceId)
		{
			if (sourceId == null)
			{
				return null;
			}
			var list = this.Query<Datas.BanishedProductBySource>(i => i.SourceId == sourceId || i.SourceId == "all");
			var result = new List<Models.BanishedProduct>();
			if (list != null)
			{
				foreach (var item in list)
				{
					result.Add(item.ToBanishedProduct());
				}
			}
			return result;
		}

		public IEnumerable<Models.BanishedProduct> GetBanishedProductListByFilter(Models.BanishedProductListFilter filter, out int count)
		{
			var list = GetAllBanishedProduct();

			if (filter.HasReleaseDate.HasValue)
			{
				list = list.Where(i => i.ReleaseDate.HasValue);
			}

			if (filter.ProductId.HasValue)
			{
				list = list.Where(i => i.ProductId == filter.ProductId.Value);
			}

			if (filter.SourceId != null)
			{
				list = list.Where(i => i.SourceId == filter.SourceId);
			}

			if (!filter.SortColumnName.IsNullOrTrimmedEmpty())
			{
				if (filter.SortDirection == System.ComponentModel.ListSortDirection.Ascending)
				{
					list = list.OrderBy(filter.SortColumnName);
				}
				else
				{
					list = list.OrderByDescending(filter.SortColumnName);
				}
			}
			else
			{
				list = list.OrderBy(i => i.Id);
			}

			count = list.Count();
			var pagedList = list.Skip(filter.PageIndex * filter.PageSize).Take(filter.PageSize).ToList();
			var result = new List<Models.BanishedProduct>();
			foreach (var item in pagedList)
			{
				result.Add(item.ToBanishedProduct());
			}
			return result;
		}

		public void SaveBanishedProduct(BanishedProduct item)
		{
			var data = this.Get<Datas.BanishedProductBySource>(i => i.SourceId == item.SourceId && i.ProductId == item.ProductId);
			bool isNewRecord = false;
			if (data == null)
			{
				data = new Datas.BanishedProductBySource();
				isNewRecord = true;
			}
			data.ProductId = item.ProductId;
			data.SourceId = item.SourceId;
			data.ReleaseDate = item.ReleaseDate;
			if (isNewRecord)
			{
				this.Insert(data);
			}
			else
			{
				Update(data);
			}
		}

		public void DeleteBanishedProduct(Models.BanishedProduct model)
		{
			var existing = Get<Datas.BanishedProductBySource>(i => i.SourceId == model.SourceId && i.ProductId == model.ProductId);
			if (existing != null)
			{
				Delete(existing);
			}
		}

		private IQueryable<Repositories.Datas.BanishedProductBySource> GetAllBanishedProduct()
		{
			var result = this.Query<Datas.BanishedProductBySource>();

			return result;
		}
	}
}
